package custom.security.browser;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 自定义的UserDetailsService实现类(示例，不建议直接应用)
 * Created by wgt on 2017/10/12.
 */
@Slf4j
@Component
public class CustomUserDetailsService implements UserDetailsService {

    /**
     * 用户信息数据源，可自行开发中用ORM框架从数据库获取信息
     */
    private static ConcurrentHashMap<String,String> users = new ConcurrentHashMap<>();
    static {
        users.put("admin","123qwe");
        users.put("user","123456");
        users.put("wgt","wgt110");
    }

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 加载用户详情
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        log.info("user login by username: {}",username);

        if (StringUtils.isBlank(username))throw new UsernameNotFoundException("username can not be empty.");

        for (Map.Entry<String,String> user:users.entrySet()){
            if (user.getKey().equals(username)){
                return new User(user.getKey(),passwordEncoder.encode(user.getValue()),  //use passwordEncoder to encode password
                        Boolean.TRUE,       // is not enabled ?
                        Boolean.TRUE,       // is not accountNonExpired ?
                        Boolean.TRUE,       // is not credentialsNonExpired ?
                        Boolean.TRUE,       // is not accountNonLocked ?
                        AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
            }
        }

        throw new UsernameNotFoundException("not found user by username-->"+username);
    }

}
